﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Hosting;
using MiniErp.Entity.DataStreams.BOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MiniErp.Core.Filters
{
    /// <summary>
    /// 异常拦截器
    /// </summary>
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly IModelMetadataProvider _modelMetadataProvider;

        public ExceptionFilter(
            IWebHostEnvironment hostingEnvironment,
            IModelMetadataProvider modelMetadataProvider)
        {
            _hostingEnvironment = hostingEnvironment;
            _modelMetadataProvider = modelMetadataProvider;
        }

        public void OnException(ExceptionContext context)
        {
            var result = context.Exception as ExceptionBO;
            context.Result = result == null
                ? context.Exception.Source.Contains("Microsoft.EntityFrameworkCore")
                //EF异常
                ? new JsonResult(new
                {
                    Status = false,
                    Code = 400,
                    Message = context.Exception.Message,
                })
                //未知异常
                : new JsonResult(new
                {
                    Status = false,
                    Code = 500,
                    Message = context.Exception.Message
                })
                //业务异常
                : new JsonResult(new
                {
                    Status = false,
                    Code = result.Code,
                    Message = result.Message
                });
            Console.WriteLine(context.Exception);
            //如果是服务器异常则存错误日志

        }
    }
}
